"""
    Author:
    Date: 2019-10-21

    banner管理类
"""

from utils import db


def get_banner(banner_id):
    """ 根据id获取banner """
    sql = f'''
        SELECT      *
        FROM        cmf_config_banner
        WHERE       id={banner_id};
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def get_banner_list(banner_type):
    """ 获取指定类型的banner列表 """
    sql = f'''
        SELECT      *
        FROM        cmf_config_banner
        WHERE       type={banner_type}
        ORDER BY    enabled DESC,
                    orderno,
                    id;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def enable_banner(banner_id):
    """ 启用banner """
    sql = f'''
        UPDATE      cmf_config_banner
        SET         enabled=1
        WHERE       id={banner_id} AND
                    enabled=0;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows > 0


def disable_banner(banner_id):
    """ 启用banner """
    sql = f'''
        UPDATE      cmf_config_banner
        SET         enabled=0
        WHERE       id={banner_id} AND
                    enabled=1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows > 0


def edit_banner(banner_id, name, orderno, image_url, link_url):
    """ 编辑banner """
    sql = f'''
        UPDATE      cmf_config_banner
        SET         name=%(name)s,
                    orderno=%(orderno)s,
                    image_url=%(image_url)s,
                    link_url=%(link_url)s
        WHERE       id=%(banner_id)s;
    '''
    params = {
        'banner_id': str(banner_id),
        'name': name,
        'orderno': str(orderno),
        'image_url': image_url,
        'link_url': link_url,
    }
    affected_rows = db.execute_sql(sql, params)
    return affected_rows > 0


def new_banner(bundle_id, banner_type, name, orderno, image_url, link_url):
    """ 添加新的banner """
    sql = '''
        INSERT INTO cmf_config_banner
        SET         bundle_id=%(bundle_id)s,
                    type=%(banner_type)s,
                    name=%(name)s,
                    orderno=%(orderno)s,
                    image_url=%(image_url)s,
                    link_url=%(link_url)s,
                    enabled=0
    '''
    params = {
        'bundle_id': bundle_id,
        'banner_type': str(banner_type),
        'name': name,
        'orderno': str(orderno),
        'image_url': image_url,
        'link_url': link_url,
    }
    affected = db.execute_sql(sql, params)
    return affected == 1


if __name__ == '__main__':
    print('ok')

